package com.lrd.snapshotorder.service.orderconsumer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class OrderExecutorPool {

    private Map<Integer, ThreadPoolExecutor> threadPoolExecutorMap = new ConcurrentHashMap<>();


    /**
     * 一个根据订单批次号动态获取的线程池，用完后销毁
     *
     * @param batchNumber
     * @return
     */
    public ThreadPoolExecutor dynamicThreadPool(Integer batchNumber) {
        synchronized (OrderExecutorPool.class) {
            if (threadPoolExecutorMap.get(batchNumber) == null) {
                synchronized (OrderExecutorPool.class) {
                    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                            100,
                            200,
                            60L,
                            TimeUnit.SECONDS,
                            new LinkedBlockingDeque<>(10000),
                            runnable -> new Thread(runnable, "JobTriggerHelper-fastTriggerPool" + runnable.hashCode())
                    );
                    threadPoolExecutorMap.put(batchNumber, threadPoolExecutor);
                    return threadPoolExecutor;
                }
            }
            return threadPoolExecutorMap.get(batchNumber);
        }
    }
}
